/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import QtQuick 2.12
import QtQml 2.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import org.ukui.tablet 1.0
import "./baseComponent"
import "."

Window {
    id: rootWindow;
    function setClassify() {
        var setClassifyPage = 0;
        if(setClassifyId === CategoryItem.All) {
            listview.highlightMoveDuration = 0;
            listview.currentIndex = 0;
        }
        else {
            for(var i = 0; i < repeater.count; i++) {
                if(categroyList[i] === setClassifyId) {
                    listview.highlightMoveDuration = 0;
                    listview.currentIndex = setClassifyPage;
                    return;
                }
                setClassifyPage += pageList[i];
            }
            listview.highlightMoveDuration = 0;
            listview.currentIndex = 0;
        }
    }

    property int buttonWidth: 96;
    property int buttonImageWidth: 40;
    property int buttonRadius: 12;
    property int buttonGroupY: 111;
    property int buttonSpace: 24;
    property int imagetextSpace: 8;

    property int listviewTopMargin: 120;
    property int listviewWidth: 1050;
    property int listviewHeight: 520;

    property int indicatorTopMargin: 50;

    property int bottomButtonWidth: 240;
    property int bottomButtonHeight: 48;
    property int okcancelButtonSpace: 32;
    property int okcancelButtonTopMargin: 40;
    property int buttomButtonRadius: 12;

    property var pageList: new Array;
    property var selectedIds: new Array;
    property var categroyList: new Array;
    property var categoryName: new Array;

    property string classifyText;
    property int setClassifyId: CategoryItem.All;

    property int currentPageCount: 0;
    property int currentInGroup: 0;
    property int beforePageCount: 0;

    // 打开添加界面时所在的分组id
    property int groupId: 0
    // 打开添加界面时所在的分组内的页
    property int groupPageIndex: 0
    property bool flag: false

    visible: false;
    color: "transparent"
    flags: Qt.FramelessWindowHint    
    onSetClassifyIdChanged: setClassify();

    Rectangle {
        anchors.fill: parent
        color: Qt.rgba(0, 0, 0, 0.6)

        ButtonGroup {
            id: buttongroup;
            buttons: repeater.children;
        }        

        Row {
            id: buttonCategory;
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.top: parent.top
            anchors.topMargin: 100 * Style.widthScaleFactor;
            spacing: buttonSpace * Style.widthScaleFactor;
            Repeater {
                id: repeater;
                model: modelManager.categoryModel;
                delegate: buttonDelegate;
            }
        }

        Component {
            id: buttonDelegate;
            Button {
                id: button;

                property int classifyEnum: modelData.category;
                width: buttonWidth * Style.widthScaleFactor;
                height: buttonWidth * Style.heightScaleFactor;
                checkable: true;
                autoExclusive: true;
                onCheckedChanged: classifyText = icontext.text;
                background: Rectangle {
                    id: imagetext;
                    width:  buttonWidth * Style.widthScaleFactor;
                    height: buttonWidth * Style.heightScaleFactor;
                    radius: buttonRadius;
                    color: {
                        if(mouse.pressed) {
                            return "#262626";
                        }
                        else {
                            return button.checked ? "#ffffff" : "#262626";
                        }
                    }
                    opacity: {
                        if(mouse.pressed) {
                            return 0.4;
                        }
                        else {
                            return button.checked ? 0.75 : 0.2;
                        }
                    }

                    MouseArea {
                        id: mouse;
                        anchors.fill: parent;
                        property int j: 0;
                        onClicked: {
                            j = 0;
                            for(var i=0;i < repeater.count;i++) {
                                if(i === index) {
                                    if(listview.currentIndex > j && listview.currentIndex - j >= 2) {
                                        repeater.itemAt(index).checked = true;
                                        flag = true
                                        listview.highlightMoveDuration = 500;
                                        listview.currentIndex -= 1;
                                        timer.start()
                                        return;
                                    }
                                    else if(listview.currentIndex < j && j - listview.currentIndex >= 2) {
                                        repeater.itemAt(index).checked = true;
                                        flag = true
                                        listview.highlightMoveDuration = 500;
                                        listview.currentIndex += 1;
                                        timer.start()
                                        return;
                                    }
                                    else {
                                        flag = false
                                        listview.highlightMoveDuration = 500;
                                        listview.currentIndex = j;
                                        return;
                                    }
                                }
                                j += pageList[i];
                            }
                        }
                    }
                    Timer {
                        id: timer
                        interval: 350
                        onTriggered: {
                            flag = false
                            listview.highlightMoveDuration = 0
                            listview.currentIndex = mouse.j
                        }
                    }
                }
                Rectangle {
                    anchors.fill: imagetext;
                    color: "transparent";
                    Column {
                        spacing: imagetextSpace * Style.heightScaleFactor;
                        anchors.centerIn: parent;
                        Rectangle {
                                width: buttonImageWidth * Style.widthScaleFactor;
                                height: buttonImageWidth * Style.heightScaleFactor;
                                color: "transparent";
                                anchors.horizontalCenter: parent.horizontalCenter;
                            Image {
                                id: image;
                                width: 30 * Style.widthScaleFactor;
                                height: 30 * Style.heightScaleFactor;
                                source: button.checked ? modelData.clickIcon : modelData.normalIcon;
                                anchors.centerIn: parent;
                            }
                        }
                        Text {
                            id: icontext;
                            width: (buttonWidth - 5) * Style.widthScaleFactor;
                            elide: Text.ElideRight;
                            horizontalAlignment: Text.AlignHCenter;
                            verticalAlignment: Text.AlignVCenter;
                            text: modelData.name;
                            font.styleName: "Noto Sans CJK SC Regular";
                            font.pointSize: Style.widthScaleFactor * 12;
                            color: button.checked ? "#262626" : "#FFFFFF";
                            anchors.horizontalCenter: parent.horizontalCenter;
                        }
                    }
                }
                Component.onCompleted: {
                    pageList.splice(index,0,modelData.pageCount);
                    categroyList.splice(index,0,modelData.category);
                }
            }
        }

        Rectangle {
            id: classifyName;
            width: 151 * Style.widthScaleFactor;
            height: 32 * Style.heightScaleFactor;
            color: "transparent";
            anchors { horizontalCenter: buttonCategory.horizontalCenter; top: buttonCategory.bottom; topMargin: 40 * Style.heightScaleFactor}
            Text {
                anchors.centerIn: parent;
                font.styleName: "苹方-简 中黑体";
                font.pointSize: Style.widthScaleFactor * 18;
                color: "#FFFFFF";
                text: classifyText;
            }
        }

        PageIndicator {
            id: pageindicator;
            anchors { horizontalCenter: listview.horizontalCenter; top: listview.bottom; topMargin: indicatorTopMargin * Style.heightScaleFactor}
            delegate: Rectangle {
                width: 8 * Style.widthScaleFactor;
                height: 8 * Style.widthScaleFactor;
                radius: pageindicator.width/2;
                color: "#FFFFFF";
                opacity: pageindicator.currentIndex === index ? 1 : 0.5;
            }
        }
        ListView {
            id: listview;
            function pageingroup() {
                currentInGroup = 0;
                beforePageCount = 0;
                currentPageCount = 0;
                for(var i=0; i< repeater.count;) {
                    currentPageCount += pageList[i];
                    currentInGroup = i;
                    if(currentIndex >= currentPageCount) {
                        beforePageCount = currentPageCount;
                        i++;
                    }
                    else {
                        return;
                    }
                }
            }
            function changePage() {
                repeater.itemAt(currentInGroup).checked = true;
                pageindicator.count = pageList[currentInGroup];
                pageindicator.opacity = (pageindicator.count === 1 ?  0 : 1)
                if(currentIndex >= pageList[0]) {
                    pageindicator.currentIndex = currentIndex - beforePageCount;
                }
                else {
                    pageindicator.currentIndex = currentIndex;
                }
            }
            anchors { horizontalCenter: classifyName.horizontalCenter; top: classifyName.bottom; topMargin: 35 * Style.heightScaleFactor}
            width: listviewWidth * Style.widthScaleFactor;
            height: listviewHeight * Style.heightScaleFactor;
            model: modelManager.categoryItemsModel;
            delegate: gridview;
            visible: true;
            clip: true;
            orientation: ListView.Horizontal;
            snapMode: ListView.SnapOneItem;
            highlightRangeMode: ListView.StrictlyEnforceRange;//切换item的时候currentIndex也跟随着变化
            highlightMoveDuration: 0;

            onCurrentIndexChanged: {

                if (pageList.length === 0){
                    console.log("null");
                    return;
                }
                if(flag) {
                    return;
                }
                listview.pageingroup();
                listview.changePage();
            }
        }
        Component {
            id: gridview;
            GridView {
                cellHeight: 130 * Style.heightScaleFactor;
                cellWidth: 150 * Style.widthScaleFactor;
                width: listview.width + 10
                height: listview.height
                model: modelData;
                delegate: appShow;
            }
        }

        Component {
            id: appShow;
            Rectangle {
                width: 150 * Style.widthScaleFactor;
                height: 130 * Style.heightScaleFactor;
                color: "transparent";
                AppIcon {
                    id: item;
                    appIconSource: "image://icons/" + modelData.icon;
                    iconWidth: Style.widthScaleFactor * 64;
                    iconRadius: Style.widthScaleFactor * 12;
                    iconState: modelData.state;
                    anchors.horizontalCenter: parent.horizontalCenter;
                    anchors.verticalCenter: parent.verticalCenter;
                    selected: modelData.selected;
                    eduAppId: modelData.id
                    eduAppPageIndex: modelData.pageIndex
                }
                Text {
                    text: modelData.name;
                    width: 130 * Style.widthScaleFactor;
                    elide: Text.ElideRight;
                    font.pointSize: Style.widthScaleFactor * 11
                    font.styleName: "Noto Sans CJK SC Regular";
                    anchors.top: item.bottom;
                    anchors.topMargin: 12 * Style.heightScaleFactor;
                    anchors.horizontalCenter: parent.horizontalCenter;
                    color: "#FFFFFF";
                    horizontalAlignment: Text.AlignHCenter;
                    verticalAlignment: Text.AlignVCenter;
                }
            }
        }
        Row {
            id: okcancelButton;
            spacing: okcancelButtonSpace * Style.widthScaleFactor;
            anchors { horizontalCenter: pageindicator.horizontalCenter; top: pageindicator.bottom; topMargin: okcancelButtonTopMargin * Style.heightScaleFactor}
            Rectangle {
                id: cancelButton;
                width: bottomButtonWidth * Style.widthScaleFactor;
                height: bottomButtonHeight * Style.heightScaleFactor;
                radius: buttomButtonRadius;
                color: "#ffffff";
                opacity: 0.4;
                Text {
                    id: cancelText;
                    text: qsTr("Cancel")
                    anchors.centerIn: parent;
                    color: "#FFFFFF";
                    font.styleName: "Noto Sans CJK SC Regular";
                    font.pointSize: Style.widthScaleFactor * 17;
                }
                MouseArea {
                    anchors.fill: parent;
                    onPressed: cancelButton.opacity = 0.2;
                    onReleased: cancelButton.opacity = 0.4;
                    onClicked: {
                        rootWindow.close()
                    }
                }
            }
            Rectangle {
                id: okButton;
                width: bottomButtonWidth * Style.widthScaleFactor;
                height: bottomButtonHeight * Style.heightScaleFactor;
                radius: buttomButtonRadius * Style.widthScaleFactor;
                color: "#00A4F4";
                Text {
                    id: okText;
                    text: qsTr("OK")
                    anchors.centerIn: parent;
                    color: "#FFFFFF";
                    font.styleName: "Noto Sans CJK SC Regular";
                    font.pointSize: Style.widthScaleFactor * 17;
                }
                MouseArea {
                    anchors.fill: parent;
                    onPressed: okButton.color = "#0092E2";
                    onReleased: okButton.color = "#00A4F4";
                    onClicked: {
                        okButton.color = "#00A4F4";
                        okButton.opacity = 1;
                        cancelButton.color = "#ffffff";
                        cancelButton.opacity = 0.4;
                        modelManager.updateGroupItems(rootWindow.groupId, rootWindow.groupPageIndex)
                        rootWindow.close()
                    }
                }
            }
        }
    }

    BlurHelper {
        id: blurHelper
        window: rootWindow
    }
    onVisibleChanged: {
        if (visible) {
            blurHelper.updateBlur()
            setClassify();
        }
    }
    Component.onCompleted: {       
        modelManager.categoryRemoved.connect(
                function(category) {
                    for(var i = 0; i < repeater.count; i++) {
                        if(categroyList[i] === category) {
                            if(pageList[i] - 1 <= 0) {
                                pageList.splice(i,1);
                                categroyList.splice(i,1);
                                if(category === setClassifyId) {
                                    listview.highlightMoveDuration = 0;
                                    listview.currentIndex = 0;
                                }
                            }
                            return;
                        }
                    }
                }
        )

        modelManager.categoryAdded.connect(
                function(category) {
                    var j = 0;
                    listview.highlightMoveDuration = 500
                    for(var i = 0; i < repeater.count; i++) {
                        if(categroyList[i] === category) {
                            if(pageList[i] === 1) {
                                if(category === setClassifyId) {
                                    listview.highlightMoveDuration = 0;
                                    listview.currentIndex = j;
                                }
                            }
                            return;
                        }
                        j += pageList[i];
                    }
                }
        )

        modelManager.categoryPageAdded.connect(
                function(category) {
                    listview.highlightMoveDuration = 500
                    for(var i = 0; i < repeater.count; i++) {
                        if(categroyList[i] === category) {
                            pageList.splice(i, 1, pageList[i] + 1);
                            listview.pageingroup();
                            listview.changePage();
                            return;
                        }
                    }
                }
        )

        modelManager.categoryPageRemoved.connect(
                function(category) {
                    for(var i = 0; i < repeater.count; i++) {
                        if(categroyList[i] === category) {
                            pageList.splice(i, 1, pageList[i] - 1);
                            listview.pageingroup();
                            listview.changePage();
                            return;
                        }
                    }
                }
        )
    }
}

